const Base = require('../../base.js');
const crypto = require('crypto');
var request = require('request')
/*获取token*/
module.exports = class extends Base {
    async indexAction() {
        const appkey = this.config('GappKey')
        const mastersecret = this.config('masterSecret')
        const timestamp = `${new Date().getTime()}`
        const miwen = appkey + timestamp + mastersecret
        const sign = crypto.createHash('SHA256').update(miwen).digest('hex');
        const cs = {
            "sign": sign,
            "timestamp": timestamp,
            "appkey": appkey
        }
    
        const cacheToken = await this.cache('Gtoken');
        let token = ''
      
        if (cacheToken) {
            token = cacheToken
        } else {
            let tokenData = await this.getTokens(cs)
            console.log(tokenData);
            console.log('8888');
            token = tokenData.token
            await this.cache('Gtoken', token, {
                timeout: 2 * 60 * 60 * 1000
            });
        }

        this.success(token)
    }
    getTokens(data) {
        return new Promise((resolve, reject) => {
            request({
                url: this.config('BaseUrl') + '/auth',
                method: 'POST',
                headers: {
                    "content-type": "application/json;charset=utf-8"
                },
                body: JSON.stringify(data)
            }, function (err, response, body) {
              console.log(err);
              console.log(response);
              console.log(body);
                body = JSON.parse(body)
                let data = body.data
                resolve(data)
            });
        })

    };

}
